/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dafe.partyband.db.api;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.config.FileConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import org.dafe.partyband.db.api.IBandManager;
import org.dafe.partyband.db.api.IBandModelFactory;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbPreferences;


/**
 *
 * @author dafe
 */
public final class DbManager {

    private static final String MAIN_DIR_NAME = ".partyband";
    private static final String MAIN_FILE_NAME = "partyband.db";
    private static final String BLOBS_DIR = "resources";

    private static String getDbBlobsPath(String rootDir) {
        return new StringBuilder(rootDir).append(File.separator).append(BLOBS_DIR).toString();
    }

    private static String getDbMainFilePath(String rootDir) {
        return new StringBuilder(rootDir).append(File.separator).append(MAIN_FILE_NAME).toString();
    }

    public static enum LocationType { LOCAL, CLIENT, SERVER };

    private static LocationType locationType = LocationType.LOCAL;
    private static String localDir;
    private static final String LOCATION_TYPE_PROP = "locationType";
    private static final String LOCAL_DIR_PROP = "localDir";
    private static final Preferences prefs = NbPreferences.forModule(DbManager.class);

    private static volatile ObjectContainer dbInstance;
    private static IBandManager bandManager;

    static {
        // reading of properties
        localDir = prefs.get(LOCAL_DIR_PROP,
                System.getProperty("user.home") + File.separator + MAIN_DIR_NAME);
        String locTypeName = prefs.get(LOCATION_TYPE_PROP, null);
        if (locTypeName != null) {
            for (LocationType locType : LocationType.values()) {
                if (locType.equals(LocationType.valueOf(locTypeName))) {
                    locationType = locType;
                    break;
                }
            }
        }
    }

    public static void setLocalContainer (String dbDir) {
        closeObjectContainer();
        dbInstance = createLocalContainer(new File(dbDir));
        getBandManager().setObjectContainer(dbInstance);
    }

    public static String getLocalDir () {
        return localDir;
    }

    public static LocationType getLocationType () {
        return locationType;
    }

    public static ObjectContainer getObjectContainer () {
        if (dbInstance == null) {
            dbInstance = createLocalContainer(new File(localDir));
        }
        return dbInstance;
    }

    public static void closeObjectContainer () {
        if (dbInstance != null) {
            dbInstance.close();
            dbInstance = null;
        }
    }

    public static IBandManager getBandManager () {
        if (bandManager == null) {
            IBandModelFactory factory = Lookup.getDefault().lookup(IBandModelFactory.class);
            bandManager = factory.createBandManager(getObjectContainer());
        }
        return bandManager;
    }

    private static ObjectContainer createLocalContainer (File dir) {
        localDir = dir.getPath();
        locationType = LocationType.LOCAL;
        prefs.put(LOCAL_DIR_PROP, localDir);
        prefs.put(LOCATION_TYPE_PROP, locationType.name());

        dir.mkdirs();
        EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
        FileConfiguration fileConfig = configuration.file();
        try {
            fileConfig.blobPath(getDbBlobsPath(localDir));
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        return Db4oEmbedded.openFile(configuration, getDbMainFilePath(localDir));
    }

}
